package com.sunwayworld.basemodule.rm.materialapply.service.impl;

import com.sunwayworld.basemodule.rm.material.bean.LimsMaterialBean;
import com.sunwayworld.basemodule.rm.material.service.LimsMaterialService;
import com.sunwayworld.framework.utils.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.sunwayworld.framework.at.annotation.AuditTrailType;
import com.sunwayworld.framework.at.annotation.AuditTrailEntry;
import com.sunwayworld.framework.spring.annotation.GikamBean;

import com.sunwayworld.basemodule.rm.materialapply.dao.LimsMaterialOutDao;
import com.sunwayworld.basemodule.rm.materialapply.bean.LimsMaterialOutBean;
import com.sunwayworld.basemodule.rm.materialapply.service.LimsMaterialOutService;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.restful.data.RestJsonWrapperBean;

import java.util.ArrayList;
import java.util.List;

@Repository
@GikamBean
public class LimsMaterialOutServiceImpl implements LimsMaterialOutService {

    @Autowired
    private LimsMaterialOutDao limsMaterialOutDao;

    @Autowired
    @Lazy
    private LimsMaterialService limsMaterialService;

    @Override
    @SuppressWarnings("unchecked")
    public LimsMaterialOutDao getDao() {
        return limsMaterialOutDao;
    }

    @Override
    @Transactional
    @AuditTrailEntry(AuditTrailType.INSERT)
    public Long insert(RestJsonWrapperBean jsonWrapper) {
        List<LimsMaterialOutBean> inserts = new ArrayList<>();

        List<LimsMaterialBean> materialBeans = jsonWrapper.parse(LimsMaterialBean.class);
        Long applyId = NumberUtils.parseLong(jsonWrapper.getParamValue("applyId"));
        String batchNo = jsonWrapper.getParamValue("batchNo");
        if (materialBeans.isEmpty() || applyId == 0L) {
            return 0L;
        }
        materialBeans.forEach(m -> {
            LimsMaterialOutBean materialOutBean = new LimsMaterialOutBean();
            materialOutBean.setMatCode(m.getMatCode());
            materialOutBean.setMatName(m.getMatName());
            materialOutBean.setMatNum(m.getMatNum());
            materialOutBean.setId(ApplicationContextHelper.getNextIdentity());
            materialOutBean.setApplyId(applyId);
            materialOutBean.setBatchNo(batchNo);
            inserts.add(materialOutBean);
        });

        if (!inserts.isEmpty()) {
            getDao().insert(inserts);
        }
        return 1L;
    }

}
